<template>
  <div class="card-table">
    <a-card type="default">
      <div class="card-table-head" v-if="title">
        <div class="card-table-head-title">{{ title }}</div>
        <div class="card-table-head-remark" v-if="selectList">
          <a-select
            class="select-title"
            placeholder="全部"
            :allowClear="false"
            v-model:value="localSelected"
            :options="selectList"
            :showSearch="true"
            @change="onSelectChange"
          />
        </div>
        <!-- v-if="exportData && !getIsMobile" -->
        <div class="card-table-head-remark">
          <a-button type="link" @click="handleExport">
            <template #icon><download-outlined /></template>
          </a-button>
        </div>
      </div>
      <div class="card-table-content">
        <a-skeleton :loading="loading">
          <a-table
            :columns="columns"
            :data-source="dataList"
            :scroll="scroll || { x: '100%' }"
            :customRow="customRowStyle"
            :mZoomType="mZoomType"
            :summary="summary"
            :pagination="isPagination"
            :onChange="onChange"
            @change="handleChange"
            rowKey="hotelName"
          >
            <template #[slotName]="{ text, record }" v-for="(slotFn, slotName) in dynamicSlots" :key="slotName">
              <slot :name="slotName" v-bind="{ text, record }">
                <span :class="{ 'main-content-title-custom': checkTag(text) }">{{ text }}</span>
              </slot>
            </template>
            <template #summary>
              <a-table-summary v-if="summary">
                <a-table-summary-row>
                  <template v-for="(column, index) in columns" :key="column.key">
                    <a-table-summary-cell :index="index">
                      <template v-if="summary">
                        <span :class="{ 'sum-title': index === 0 }" v-if="summary()[0]">
                          <span v-for="item2 in Object.keys(summary()[0])">
                            <span v-if="item2 === column.dataIndex">
                              {{summary()[0][column.dataIndex]}}
                            </span>
                          </span>
                        </span>
                      </template>
                    </a-table-summary-cell>
                  </template>
                </a-table-summary-row>
              </a-table-summary>
            </template>
          </a-table>
        </a-skeleton>
      </div>
    </a-card>
  </div>
</template>
<script>
  import { Card, Table, Select, Skeleton, Button } from 'ant-design-vue';
  import { DownloadOutlined } from '@ant-design/icons-vue';
  import * as XLSX from 'xlsx-js-style';
  import { useAppInject } from '/@/hooks/web/useAppInject';

  export default {
    name: 'TableCard',
    components: {
      ACard: Card,
      ATable: Table,
      ASelect: Select,
      ASkeleton: Skeleton,
      AButton: Button,
      DownloadOutlined,
    },
    setup() {
      const { getIsMobile } = useAppInject();
      return {
        getIsMobile,
      };
    },
    data() {
      return {
        localSelected: this.selected,
      };
    },
    mounted() {
      window.addEventListener('resize', this.handleResize);
    },
    beforeUnmount() {
      window.removeEventListener('resize', this.handleResize);
    },
    watch: {
      selected(val) {
        this.localSelected = val;
      },
      dataList: {
        handler(newVal) {
          console.log('TableCard dataList changed:', newVal);
        },
        deep: true,
      },
    },
    props: {
      title: String,
      columns: Array,
      dataList: Array,
      customRow: Function,
      onClick: Function,
      summary: Function,
      scroll: Object,
      mZoomType: String,
      selected: Object,
      selectList: Array,
      handleSelectChange: Function,
      exportData: Array,
      exportHeader: Array,
      exprotMerges: Array,
      loading: Boolean,
      isPagination: Boolean,
      pagination: Object,
      onChange: Function,
    },
    computed: {
      dynamicSlots() {
        let slots = {};
        // 结合普通插槽和作用域插槽
        // const allSlots = { ...this.$slots, ...this.$scopedSlots };
        // Vue 2 使用 $scopedSlots，Vue 3 使用 $slots
        const allSlots = this.$slots || this.$scopedSlots || {};
        // 筛选出以 'table.' 开头的插槽
        for (const slotName in allSlots) {
          if (slotName.startsWith('table.')) {
            slots[slotName] = allSlots[slotName];
          }
        }
        return slots;
      },
    },
    methods: {
      checkTag(key) {
        return typeof key === 'string' && key.includes('小计');
      },
      handleResize() {
        // this.isMobile = device.mobile;
      },
      handleChange(p) {
        if (this.onChange) {
          this.onChange(p);
        }
      },
      onSelectChange(value) {
        this.localSelected = value;
        if (this.handleSelectChange) {
          this.handleSelectChange(value);
        }
      },
      customRowStyle(record) {
        return {
          class: {
            'summary-row': this.checkTag(record.hotelName),
          },
        };
      },
      customRenderData(data, columns) {
        columns.forEach((c) => {
          if (c.customRender && data[c.dataIndex] !== undefined) {
            const value = { text: data[c.dataIndex] };
            data[c.dataIndex] = c.customRender(value);
          }
          if (c.children) {
            this.customRenderData(data, c.children);
          }
        });
      },
      handleExport() {
        let hearder = [];
        if (this.exportHeader) {
          hearder = this.exportHeader;
        } else {
          hearder = [this.columns.map((c) => c.title)];
        }

        const _columns = this.columns;
        let newData = this.exportData.map((item) => {
          let newItem = { ...item };
          const indexs = _columns.map((c) => c.dataIndex);

          // 处理数据格式化
          this.customRenderData(newItem, _columns);

          // 按列顺序组织数据
          const newDataList = [];
          indexs.forEach((i) => {
            if (newItem.hasOwnProperty(i) && i !== 'key') {
              newDataList.push(newItem[i]);
            }
          });
          return newDataList;
        });

        if (this.summary) {
          let sumData = this.summary();
          const newSumData = sumData.map((s) => {
            const newDataList = [];
            const indexs = _columns.map((c) => c.dataIndex);
            indexs.forEach((i) => {
              if (s.hasOwnProperty(i) && i !== 'key') {
                newDataList.push(s[i]);
              }
            });
            return newDataList;
          });
          newData = newData.concat(newSumData);
        }

        const datas = hearder.concat(newData);
        const worksheet = XLSX.utils.aoa_to_sheet(datas);

        if (this.exprotMerges) {
          worksheet['!merges'] = this.exprotMerges;
        }

        const range = XLSX.utils.decode_range(worksheet['!ref']);

        // 设置单元格格式
        for (let R = range.s.r; R <= range.e.r; ++R) {
          for (let C = range.s.c; C <= range.e.c; ++C) {
            const cell_address = { c: C, r: R };
            const cell_ref = XLSX.utils.encode_cell(cell_address);
            if (!worksheet[cell_ref]) continue;

            const cell = worksheet[cell_ref];
            if (typeof cell.v === 'string') {
              // 检查是否包含小计或合计
              if (cell.v.includes('小计') || cell.v.includes('合计')) {
                cell.s = { font: { color: { rgb: '00B578' } } };
              }
              // 尝试转换为数字
              const num = Number(cell.v);
              if (!isNaN(num)) {
                cell.v = num;
                cell.t = 'n';
              }
            }
          }
        }

        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
        XLSX.writeFile(workbook, `${this.title}.xlsx`);
      },
    },
  };
</script>
<style lang="less" scoped>
  @desktop: ~'screen and (min-width: 992px)';
  @mobile: ~'screen and (max-width: 991px)';

  @media @desktop {
    .ant-card-bordered {
      border: none;
    }
    ::v-deep .ant-table-thead > tr > th {
      background: #eaecf1 !important;
      color: #1a253b;
      font-weight: 500;
    }
    ::v-deep .ant-table-thead > tr > th.table-header-color {
      background: #e7f1fd !important;
    }
    ::v-deep .ant-table-summary {
      // position: sticky;
      // bottom: 0;
      // z-index: 2;
      td {
        background: #e7f1fd;
        border-bottom: none !important;
        padding: 12px 15px 12px 5px !important;
        text-align: right;
        color: #1a253b;
        font-weight: 600;
      }
      td:first-child {
        text-align: left;
        background: #e7f1fd !important;
      }
      td.ant-table-cell-fix-left {
        background: #e7f1fd !important;
      }
      .sum-title {
        font-weight: 500;
        // color: #00b578;
        padding-left: 10px;
        text-align: left;
      }
    }

    ::v-deep .ant-table-tbody > tr:last-child > td {
      border-bottom: 1px solid #f0f0f0;
    }

    ::v-deep .ant-table-tbody > tr.ant-table-row:hover > td {
      background: #f5f5f5;
    }

    .card-table {
      @media @desktop {
        padding-bottom: 20px;
      }
      &-head {
        display: flex;
        justify-content: space-between;
        margin-bottom: 12px;

        &-title {
          font-size: 15px;
          font-weight: 600;
        }
      }
      &-content {
        &-title {
          &-custom {
            color: #00b578;
          }
        }
      }
    }
  }

  @media @mobile {
    ::v-deep .ant-table-fixed-header .ant-table-scroll .ant-table-header::-webkit-scrollbar {
      border: none;
      border-width: none;
    }

    ::v-deep .card-table-content .ant-table .ant-table-thead > tr > th {
      padding: 8px 8px;
      color: #00d4ff;
      font-size: 13px;
    }

    ::v-deep .card-table-content .ant-table-thead > tr > th {
      color: #1a253b;
      font-weight: 500;
      text-align: left;
      background: none;
      border-bottom: none;
      transition: background 0.3s ease;
    }

    ::v-deep .card-table-content thead.ant-table-thead > tr > th {
      line-height: 1.375rem;
      border-bottom: 0.5px solid #00d4ff;
      white-space: pre-wrap;
    }

    ::v-deep .card-table-content .ant-table-tbody > tr > td {
      color: #1a253b;
      font-size: 13px;
      line-height: 16px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.15);
      transition: background 0.3s;
    }

    ::v-deep .ant-table .ant-table-tbody > tr > td {
      padding: 8px 8px;
    }

    ::v-deep .card-table-content .ant-table-header {
      overflow: hidden;
      background: none;
    }

    ::v-deep .ant-table-fixed-header > .ant-table-content > .ant-table-scroll > .ant-table-body {
      position: relative;
      background: none;
    }

    ::v-deep .ant-table-fixed-header > .ant-table-content > .ant-table-scroll > .ant-table-body::after {
      width: 100%;
      display: block;
      content: '';
      position: absolute;
      background: none;
      top: 0;
    }

    ::v-deep .ant-table-fixed-left table,
    .ant-table-fixed-right table {
      width: auto;
      background: #112c4d;
    }

    ::v-deep div.summary-table .ant-table-tbody > tr {
      background: none;
    }

    ::v-deep div.summary-table {
      border-top: none;
    }

    ::v-deep .summary-table .ant-table-tbody > tr > td:not(.sum-text) {
      font-weight: 400;
    }

    ::v-deep .select-title .ant-select {
      color: #8894a8;
      font-size: 0.875rem;
      line-height: 1.25rem;
      padding: unset;
      justify-content: flex-end;
      align-items: center;
      position: relative;
      background-color: #112c4d;
    }

    ::v-deep .ant-select .ant-select-selection-item {
      color: #00d4ff;
      font-size: 13px;
      font-weight: 600;
      padding-right: 0.5rem;
      text-align: center;
      display: -webkit-box;
      overflow: hidden;
      -webkit-box-orient: vertical;
      text-overflow: ellipsis;
    }

    ::v-deep .ant-select .ant-select-arrow {
      display: flex;
      width: 1rem;
      height: 1rem;
      align-items: center;
      justify-content: center;
      font-size: 1rem;
      color: #00d4ff;
    }
  }
  ::v-deep .ant-table-tbody {
    tr {
      td {
        &:first-child {
          .main-content-title-custom {
            color: #00b578;
            font-weight: 500;
          }
        }
      }
    }
  }
  // .main-content-title-custom {
  //   color: #00b578;
  //   font-weight: 500;
  // }

  ::v-deep .ant-table-tbody {
    .summary-row {
      td:first-child {
        color: #00b578;
        font-weight: 500;
      }
    }
  }
</style>
